package com.kehutong.department.app;

import com.kehutong.common.DoveClient;
import com.kehutong.common.errcode.Result;
import com.kehutong.common.util.Token;
import com.kehutong.department.entity.ThirdConfigure;
import com.kehutong.wwin.service.entity.Corp;
import com.kehutong.wwin.service.service.CorpService;
import com.kehutong.wxapi.request.ExternalContactGetRequest;
import com.kehutong.wxapi.response.ExternalContactGetResponse;
import com.kehutong.wxapi.service.impl.ExternalContactServiceImpl;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.orm.jdbc.JdbcSession;
import org.coraframework.util.Objects;

/**
 * TODO
 * 第三方业务
 * @author zhouweipeng
 * @version 1.0
 * @date 2021/9/13 10:36
 */
@MvcAction
@ReqMapping("/kht-bin/thridBusiness")
public class ThridBusinessAction {

    @Inject
    private JdbcSession jdbcSession;
    @Inject
    private DoveClient doveClient;
    @Inject
    private ExternalContactServiceImpl externalContactService;
    @Inject
    private CorpService corpService;
    private static final Logger logger = LoggerFactory.getLogger(ThridBusinessAction.class);
    @ReqMapping("/getRedirectUrl")
    public Object getRedirectUrl(JSONObject jsonObject, Token token) throws Exception{
        String userId=jsonObject.getString("userId");  //业主
        String uuid=jsonObject.getString("uuid");  //员工
        //调用接口获取微信用户信息、userInfo、employeeInfob
        JSONObject extContent=new JSONObject();
        JSONObject userInfo=new JSONObject();
        JSONObject employeeInfo=new JSONObject();
        JSONObject params = new JSONObject();
        JSONObject sessionResult = doveClient.post("/kht-bin/session/service/get", http->http.addParam("sessionId", token.getSessionId()));
        if (sessionResult.getIntValue("code") != 200) {
            throw new NullPointerException("Oauth2Service.authorization get session 远程服务调用错误:" + sessionResult.toJSONString());
        }
        JSONObject session=sessionResult.getJSONObject("data");
        if(Objects.isNull(session)){
            throw new NullPointerException("Oauth2Service.authorization 获取Session 信息为空");
        }
        params.put("userId",uuid);
        JSONObject result = doveClient.post("/basic/employee/service/api/get", (http) -> {
            http.setBody(params.toJSONString());
        });
        if (result.getIntValue("code") == 200) {
            JSONObject data=result.getJSONObject("data");
            //封装返回
            employeeInfo.put("employeeId", uuid);  //员工
            employeeInfo.put("mobile",data.getString("mobile")); //手机号
            employeeInfo.put("avatar",data.getString("avatar")); //头像
            employeeInfo.put("name",data.getString("name")); // 姓名
            employeeInfo.put("department",data.getJSONArray("department")); //部门
            employeeInfo.put("departmentName",data.getJSONArray("departmentName"));  //部门名称
            extContent.put("employeeInfo",employeeInfo);
            Corp corp =corpService.getCropByKhtId(token.getCompanyNo());
            String accessToken=corpService.getContactAccessToken(corp);
            ExternalContactGetRequest externalContactGetRequest=new ExternalContactGetRequest();
            externalContactGetRequest.setAccessToken(accessToken);
            externalContactGetRequest.setExternalUserid(userId);
            ExternalContactGetResponse externalContactGetResponse=externalContactService.getExternalContact(externalContactGetRequest);
            if(externalContactGetResponse.getErrcode().intValue()==0){
                userInfo.put("name",externalContactGetResponse.getExternalContact().getName());
                userInfo.put("avatar",externalContactGetResponse.getExternalContact().getAvatar());
                userInfo.put("unionid",externalContactGetResponse.getExternalContact().getUnionid());
                userInfo.put("gender",externalContactGetResponse.getExternalContact().getGender());
                extContent.put("userInfo",userInfo);
            }
            //todo 修改session
            JSONObject updateParam=new JSONObject();
            updateParam.put("id",token.getSessionId());
            updateParam.put("ext",extContent);
            JSONObject changeSessionExtResult = doveClient.post("/kht-bin/session/service/changeExt", (http) -> {
                http.setBody(updateParam.toJSONString());
            });
            if (changeSessionExtResult.getIntValue("code") == 200) {
                return jdbcSession.findArray(ThirdConfigure.class).eq("deleted", false).order("createTime", "DESC").exe();
            }else{
                return Result.error(500, "系统异常!");
            }
        }else{
            return Result.error(500, "系统异常!");
        }

    }

}
